package com.biscuit.page.basicservice.design.login.factory;

import com.biscuit.page.basicservice.model.enums.LoginTypeEnum;
import com.biscuit.page.basicservice.design.login.strategy.LoginMoreTypeInterface;
import com.biscuit.page.basicservice.design.login.LoginType;
import com.biscuit.page.basicservice.utils.BaseExceptionUtil;
import lombok.Setter;
import org.springframework.beans.factory.InitializingBean;

import java.util.*;

/**
 * @author biscuit
 * @createTime 2024/5/22 13:58
 */
public class LoginMoreTypeFactory implements InitializingBean {

    @Setter
    private List<LoginMoreTypeInterface> loginMoreTypeInterfaceList;

    private Map<LoginTypeEnum, LoginMoreTypeInterface> factoryMap;

    @Override
    public void afterPropertiesSet() {
        factoryMap = new HashMap<>(this.loginMoreTypeInterfaceList.size() << 1);
        this.loginMoreTypeInterfaceList.forEach(loginMoreTypeInterface -> {
            LoginType loginType = loginMoreTypeInterface.getClass().getAnnotation(LoginType.class);
            if (Objects.isNull(loginType)) {
                return;
            }
            factoryMap.put(loginType.type(), loginMoreTypeInterface);
        });
    }

    public LoginMoreTypeInterface create(Integer type) {
        LoginTypeEnum typeEnumByType = LoginTypeEnum.getTypeEnumByType(type);
        BaseExceptionUtil.throwException(Objects.nonNull(typeEnumByType), "当前所选登录类型不存在");
        return this.factoryMap.get(typeEnumByType);
    }

}
